import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/common/state/common_net_status.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:casdon/common/widget/dialog_helpers.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/common/widget/fullscreen_loading_overlay.dart';
import 'package:casdon/common/widget/show_first_launch_agreement_dialog.dart';
import 'package:casdon/common/widget/underline_text_field.dart';
import 'package:casdon/common/widget/show_ad_dialog.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/core/utils/first_launch_service.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/login/application/notifier/login_apple_notifier.dart';

import 'package:casdon/modules/login/application/notifier/login_type_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_wechat_notifier.dart';
import 'package:casdon/modules/login/domain/states/login_code_state.dart';
import 'package:casdon/modules/login/domain/states/login_oneTap_state.dart';
import 'package:casdon/modules/login/domain/usecases/check_account_usecase.dart';
import 'package:casdon/modules/login/providers/login_apple_provider.dart';
import 'package:casdon/modules/login/providers/login_code_provider.dart';
import 'package:casdon/modules/login/providers/login_oneTap_provider.dart';
import 'package:casdon/modules/login/providers/login_provider.dart';
import 'package:casdon/modules/login/providers/login_wechat_provider.dart';
import 'package:casdon/modules/login/ui/widgets/agreement_check.dart';
import 'package:casdon/modules/login/ui/widgets/social_login_button.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';

final accountInputProvider = StateProvider.autoDispose<String>((ref) => '');

@RoutePage()
class AccountInputScreen extends ConsumerStatefulWidget {
  const AccountInputScreen({super.key});

  @override
  ConsumerState<AccountInputScreen> createState() => _AccountInputScreenState();
}

class _AccountInputScreenState extends ConsumerState<AccountInputScreen> {
  static const screenId = 'AccountInputScreen';
  static const double gapSize = 24;

  ProviderSubscription? _codeSub;
  ProviderSubscription? _appleSub;
  ProviderSubscription? _wechatSub;
  ProviderSubscription? _oneTapSub;

  @override
  void initState() {
    super.initState();
    // ✅ 生命周期中监听，build 不会重复添加监听
    _listenLoginCodeState();
    _listenLoginAppleState();
    _listenLoginWechatState();
    _listenLoginOneTapState();

    _openOneTapLogin();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _maybeShowFirstLaunchAggrementDialog();
    });
  }

  @override
  void dispose() {
    // ✅ 页面销毁时手动取消监听
    _codeSub?.close();
    _appleSub?.close();
    _wechatSub?.close();
    _oneTapSub?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final notifier = ref.watch(loginCodeProvider.notifier);
    final appleNotifier = ref.watch(loginAppleProvider.notifier);
    final wxNotifier = ref.watch(loginWechatProvider.notifier);
    final isAgreed = ref.watch(loginCodeProvider.select((s) => s.agreed));
    final accountEditingController = ref.watch(
      editingControllerProvider(screenId),
    );
    final inputValidator = ref.watch(inputValidatorProvider);
    final accountText = ref.watch(accountInputProvider);
    final isLoading = ref.watch(
      loginCodeProvider.select((s) => s.status == CommonNetStatus.loading),
    );
    final isAppleLoading = ref.watch(
      loginAppleProvider.select((s) => s.status == CommonNetStatus.loading),
    );
    final isWechatLoading = ref.watch(
      loginWechatProvider.select((s) => s.status == CommonNetStatus.loading),
    );
    final isOneTapLoading = ref.watch(
      logiOneTapProvider.select((s) => s.status == CommonNetStatus.loading),
    );
    final isBlockingLoginLoading =
        isAppleLoading || isWechatLoading || isOneTapLoading;
    final isEnabled = !isLoading;

    return Scaffold(
      resizeToAvoidBottomInset: true,
      body: Stack(
        children: [
          SafeArea(
            child: Column(
              children: [
                CommonAppBar(
                  title: "",
                  onBack: () => _openOneTapLogin(),
                  backgroundColor: Colors.transparent,
                ),
                Expanded(
                  child: KeyboardAvoider(
                    duration: const Duration(milliseconds: 300),
                    autoScroll: true,
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: gapSize.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          SizedBox(height: 44.h),
                          Image.asset(
                            'assets/images/logo_1.png',
                            width: 195.w,
                            height: 58.h,
                            fit: BoxFit.contain,
                          ),
                          SizedBox(height: 48.h),
                          UnderlineTextField(
                            hintText: '手机号或邮箱',
                            controller: accountEditingController,
                            keyboardType: TextInputType.emailAddress,
                            onChanged: (value) {
                              notifier.updateAccount(value);
                              ref.read(accountInputProvider.notifier).state =
                                  value;
                            },
                            validator: null,
                          ),
                          SizedBox(height: 16.h),
                          AgreementCheckBox(
                            value: isAgreed,
                            onChanged: (val) {
                              notifier.setAgree(val);
                              appleNotifier.setAgree(val);
                              wxNotifier.setAgree(val);
                            },
                          ),
                          SizedBox(height: 24.h),
                          PrimaryButton(
                            text: '获取验证码',
                            onPressed: isEnabled
                                ? () {
                                    _handleGetSmsCode();
                                  }
                                : null,
                            isLoading: isLoading,
                          ),
                          Row(
                            children: [
                              const Spacer(),
                              TextButton(
                                onPressed: () {
                                  ref.read(loginTypeProvider.notifier).state =
                                      LoginType.account;
                                  ref
                                          .read(accountInputProvider.notifier)
                                          .state =
                                      accountEditingController.text;
                                  context.router.push(const LoginPwdRoute());
                                },
                                child: Text(
                                  "账号密码登录",
                                  style: context.textTheme.bodyMedium?.copyWith(
                                    color: context
                                        .customColorThemeNonNull
                                        .textColor3,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 148.h),
                          Column(
                            children: [
                              Padding(
                                padding: EdgeInsets.symmetric(horizontal: 12.w),
                                child: Row(
                                  children: [
                                    const Expanded(
                                      child: Divider(
                                        thickness: 1,
                                        color: Color(0xFFE0E0E0),
                                      ),
                                    ),
                                    Padding(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 8.w,
                                      ),
                                      child: Text(
                                        '其他登录方式',
                                        style: TextStyle(
                                          color: Colors.grey,
                                          fontSize: 14.r,
                                        ),
                                      ),
                                    ),
                                    const Expanded(
                                      child: Divider(
                                        thickness: 1,
                                        color: Color(0xFFE0E0E0),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(height: 20.h),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  SocialLoginButton(
                                    iconAsset: 'assets/images/wechat_logo.png',
                                    onPressed: () async {
                                      if (!await _ensureAgreementAccepted()) {
                                        return;
                                      }
                                      ref.read(loginTypeProvider.notifier).state =
                                          LoginType.wechat;
                                      wxNotifier.auth();
                                    },
                                  ),
                                  SizedBox(width: 40.w),
                                  SocialLoginButton(
                                    iconAsset: 'assets/images/apple_logo.png',
                                    onPressed: () async {
                                      if (!await _ensureAgreementAccepted()) {
                                        return;
                                      }
                                      ref.read(loginTypeProvider.notifier).state =
                                          LoginType.apple;
                                      appleNotifier.signIn();
                                    },
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          if (isBlockingLoginLoading) const FullscreenLoadingOverlay(),
        ],
      ),
    );
  }

  // -----------------------
  // ✅ 各登录状态监听逻辑
  // -----------------------
  void _listenLoginCodeState() {
    _codeSub = ref.listenManual(loginCodeProvider, (previous, next) {
      final notifier = ref.read(loginCodeProvider.notifier);
      if (notifier.step != LoginCodeStep.sendCode) return;
      if (next.source != SendCodeSource.accountPage) return;

      if (next.status == CommonNetStatus.success) {
        ToastUtil.show(next.message ?? "获取验证码成功");
        context.router.push(CodeInputRoute(account: next.account!));
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "获取验证码失败");
      }
    });
  }

  void _listenLoginAppleState() {
    final notifier = ref.read(loginAppleProvider.notifier);
    _appleSub = ref.listenManual(loginAppleProvider, (previous, next) async {
      if (next.status == CommonNetStatus.failure) {
        if (notifier.step == AppleLoginStep.login &&
            next.errorCode == "10012") {
          final ret = await showBindPhoneConfirmDialog(context);
          if ((ret ?? false) && context.mounted) {
            BindAccountRoute(source: "APPLE").push(context);
          } else {
            ref.read(loginWechatProvider.notifier).resetStateAndStep();
          }
        } else {
          ToastUtil.show(next.message ?? "登录失败");
        }
      } else if (next.status == CommonNetStatus.success &&
          (notifier.step == AppleLoginStep.login ||
              notifier.step == AppleLoginStep.afterbindingLogin)) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (context.mounted) context.router.replaceAll(const [TabRoute()]);
        });
      }
    });
  }

  void _listenLoginWechatState() {
    final notifier = ref.read(loginWechatProvider.notifier);
    _wechatSub = ref.listenManual(loginWechatProvider, (previous, next) async {
      if (next.status == CommonNetStatus.failure) {
        if (notifier.step == WeChatLoginStep.login &&
            next.errorCode == "10012") {
          final ret = await showBindPhoneConfirmDialog(context);
          Log.i("用户选择了 $ret");
          if ((ret ?? false) && context.mounted) {
            BindAccountRoute(source: "WECHAT_OPEN").push(context);
          } else {
            ref.read(loginWechatProvider.notifier).resetStateAndStep();
          }
        } else {
          ToastUtil.show(next.message ?? "登录失败");
        }
      } else if (next.status == CommonNetStatus.success &&
          (notifier.step == WeChatLoginStep.login ||
              notifier.step == WeChatLoginStep.afterbindingLogin)) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (context.mounted) context.router.replaceAll(const [TabRoute()]);
        });
      }
    });
  }

  void _listenLoginOneTapState() {
    Log.i(" 119615 _listenLoginOneTapState");
    _oneTapSub?.close();
    _oneTapSub = ref.listenManual<LoginOnetapState>(logiOneTapProvider, (
      previous,
      next,
    ) {
      Log.i("119615 oneTap state change: ${next.status} v${next.version}");
      if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "登录失败");
      } else if (next.status == CommonNetStatus.success) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (context.mounted) {
            context.router.replaceAll(const [TabRoute()]);
          }
        });
      }
    }, fireImmediately: false);
  }

  // -----------------------
  // ✅ 一键登录
  // -----------------------
  void _openOneTapLogin() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      ref.read(loginTypeProvider.notifier).state = LoginType.oneTap;
      ref.read(logiOneTapProvider.notifier).login();
    });
  }

  Future<void> _maybeShowFirstLaunchAggrementDialog() async {
    final alreadyAccepted = await FirstLaunchService.instance
        .hasAcceptedAgreements();
    if (alreadyAccepted || !mounted) return;

    final ret = await showFirstLaunchAggrementDialog(
      context: context,
      onUserAgreementTap: () => context.router.push(
        WebPageRoute(url: CommonConfig.urser_protocol, title: ''),
      ),

      onPrivacyPolicyTap: () => context.router.push(
        WebPageRoute(url: CommonConfig.privacy_protocol, title: ''),
      ),
    );

    if (ret == true) {
      await FirstLaunchService.instance.markAgreementsAccepted();
      ref.read(loginCodeProvider.notifier).setAgree(true);
      ref.read(loginAppleProvider.notifier).setAgree(true);
      ref.read(loginWechatProvider.notifier).setAgree(true);
      ref.read(logiOneTapProvider.notifier).setAgree(true);
    }
  }

  void _handleGetSmsCode() async {
    final checkAccountUsecase = ref.read(checkAccountUsecaseProvider);
    final notifier = ref.read(loginCodeProvider.notifier);
    final state = ref.read(loginCodeProvider);
    if (!notifier.agreed()) {
      final ret = await showAgreementDialog(context);
      if (ret == true) {
        ref.read(loginCodeProvider.notifier).setAgree(true);
        ref.read(loginAppleProvider.notifier).setAgree(true);
        ref.read(loginWechatProvider.notifier).setAgree(true);
        ref.read(logiOneTapProvider.notifier).setAgree(true);
        // 同意后如果账号已填且合法，直接继续
        final accountText = state.account ?? ref.read(accountInputProvider);
        final validator = ref.read(inputValidatorProvider);
        if (accountText != null &&
            accountText.isNotEmpty &&
            validator.isValude(accountText)) {
          _continueGetSms(
            account: accountText,
            checkAccountUsecase: checkAccountUsecase,
          );
        }
      }
      return;
    }
    if (state.account == null) {
      ToastUtil.show("请输入账号");
      return;
    }
    final inputValidator = ref.watch(inputValidatorProvider);
    if (inputValidator.isValude(state.account!) == false) {
      ToastUtil.show("账号格式不正确");
      return;
    }
    await _continueGetSms(
      account: state.account!,
      checkAccountUsecase: checkAccountUsecase,
    );
  }

  Future<void> _continueGetSms({
    required String account,
    required CheckAccountUsecase checkAccountUsecase,
  }) async {
    try {
      await checkAccountUsecase.execute(userName: account);
    } on BusinessException catch (e) {
      if (e.code == "10003") {
        // 验证码登录页面，账号不存在，直接忽略，继续登录，后端会自动注册
      } else {
        ToastUtil.show(e.msg);
        rethrow;
      }
    }

    ref.read(loginTypeProvider.notifier).state = LoginType.optCode;
    ref.read(loginCodeProvider.notifier).sendCode();
  }

  Future<bool> _ensureAgreementAccepted() async {
    final agreed = ref.read(loginCodeProvider).agreed;
    if (agreed) return true;
    final ret = await showAgreementDialog(context);
    if (ret == true) {
      ref.read(loginCodeProvider.notifier).setAgree(true);
      ref.read(loginAppleProvider.notifier).setAgree(true);
      ref.read(loginWechatProvider.notifier).setAgree(true);
      ref.read(logiOneTapProvider.notifier).setAgree(true);
      return true;
    }
    return false;
  }
}
